package com.party.admin.web.controller.mall;

import com.party.admin.biz.mall.MallBrandBizService;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.admin.web.dto.output.mall.MallBrandOutput;
import com.party.common.paging.Page;
import com.party.core.exception.BusinessException;
import com.party.core.model.mall.MallBrand;
import com.party.core.model.mall.MallCategoryBrand;
import com.party.core.service.mall.IMallBrandService;
import com.party.core.service.mall.IMallCategoryBrandService;
import com.party.core.service.mall.IMallGoodsService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

/**
 * Created by huangwuming on 2018/3/27/027.
 */
@Controller
@RequestMapping("/mall/brand")
public class MallBrandController {
    @Autowired
    private IMallBrandService mallBrandService;
    @Autowired
    private IMallCategoryBrandService mallCategoryBrandService;
    @Autowired
    private IMallGoodsService mallGoodsService;
    @Autowired
    private MallBrandBizService mallBrandBizService;

    Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping(value = "list")
    public ModelAndView list(CommonInput commonInput, Page page, MallBrand goodsBrand) {
        page.setLimit(20);
        ModelAndView mv = new ModelAndView("mall/brand/brandList");
        Map<String, Object> params = CommonInput.appendParams(commonInput);
        List<MallBrandOutput> brandOutputs = mallBrandBizService.brandList(goodsBrand, params, page);

        mv.addObject("page", page);
        mv.addObject("MallGoodsBrandList", brandOutputs);
        mv.addObject("input", commonInput);
        mv.addObject("goodsBrand", goodsBrand);
        return mv;
    }

    /**
     * 主页选择品牌
     *
     * @param mallGoodsBrand
     * @param page
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "selectBrand")
    public ModelAndView selectBrand(MallBrand mallGoodsBrand, Page page) {
        page.setLimit(10);
        ModelAndView mv = new ModelAndView("mall/brand/selectBrand");
        List<MallBrand> list = mallBrandService.listPage(mallGoodsBrand, page);
        mv.addObject("page", page);
        mv.addObject("list", list);
        mv.addObject("mallGoodsBrand", mallGoodsBrand);
        return mv;
    }

    @ResponseBody
    @RequestMapping(value = "delete")
    public AjaxResult deleteBrand(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("id不能为空");
        }
        try {
            List<MallCategoryBrand> categoryBrands = mallCategoryBrandService.findByBrandId(id);
            if (categoryBrands.size() > 0) {
                return AjaxResult.error("该品牌已分配");
            }
            MallBrand mallGoodsBrand = mallBrandService.get(id);
            if (mallGoodsBrand.getGoodsNum() > 0) {
                return AjaxResult.error("该品牌已分配");
            }
            mallBrandService.delete(id);
            return AjaxResult.success();
        } catch (Exception e) {
            return AjaxResult.error("删除失败");
        }
    }

    @ResponseBody
    @RequestMapping(value = "save")
    public AjaxResult saveGoodsBrand(MallBrand mallGoodsBrand) {
        try {
            mallBrandBizService.saveBrand(mallGoodsBrand);
            return AjaxResult.success();
        } catch (BusinessException e) {
            return AjaxResult.error(e.getMessage());
        } catch (Exception e) {
            logger.error("保存品牌失败", e);
            return AjaxResult.error("保存品牌失败");
        }
    }

    /**
     * 发布或编辑商品品牌
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "brandForm")
    public ModelAndView showBrandForm(String id) {
        ModelAndView mv = new ModelAndView("mall/brand/brandForm");
        MallBrand mallGoodsBrand = null;
        if (StringUtils.isNotEmpty(id)) {
            mallGoodsBrand = mallBrandService.get(id);
        }
        mv.addObject("mallGoodsBrand", mallGoodsBrand);
        return mv;
    }

    /**
     * 添加品牌
     *
     * @return
     */
    @RequestMapping("selectBrandDialog")
    public ModelAndView selectBrandDialog(String brandIds, String type) {
        ModelAndView mv = new ModelAndView("mall/brand/brandDialog");
        List<MallBrand> brandList = mallBrandService.list(new MallBrand());
        mv.addObject("brandList", brandList);
        if (StringUtils.isNotEmpty(brandIds)) {
            String[] newBrandIds = brandIds.split(",");
            mv.addObject("useBrandIds", newBrandIds);
        }
        return mv;
    }

    /**
     * 保存分类规格
     *
     * @param categoryId
     * @param brandIds
     * @return
     */
    @ResponseBody
    @RequestMapping("saveCategoryBrand")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult saveCategorySpec(String categoryId, String brandIds) {
        if (StringUtils.isEmpty(categoryId)) {
            return AjaxResult.error("分类id不能为空");
        }

        try {
            mallCategoryBrandService.deleteByUnique(new MallCategoryBrand(categoryId, ""));

            for (String id : brandIds.split(",")) {
                MallCategoryBrand categorySpec = new MallCategoryBrand(categoryId, id);
                mallCategoryBrandService.insert(categorySpec);
            }
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存分类规格失败", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存分类规格失败");
        }
    }

    /**
     * 删除分类品牌
     *
     * @param categoryId 分类编号
     * @param brandId    品牌编号
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteCategoryBrand")
    public AjaxResult deleteCategoryBrand(String categoryId, String brandId) {
        if (StringUtils.isEmpty(categoryId) || StringUtils.isEmpty(brandId)) {
            return AjaxResult.error("分类或者品牌编号不能为空");
        }
        try {
            Integer count = mallGoodsService.checkCategoryBrand(brandId, categoryId);
            if (count > 0) {
                return AjaxResult.error("已分配，不能移除");
            }
            mallCategoryBrandService.deleteByUnique(new MallCategoryBrand(categoryId, brandId));
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("删除分类品牌失败", e);
            return AjaxResult.error("");
        }
    }

    /**
     * 验证品牌名是否存在
     *
     * @param name 品牌名称
     * @param id   品牌id
     * @return
     */
    @ResponseBody
    @RequestMapping("verifyName")
    public AjaxResult verifySpecName(String name, String id) {
        if (StringUtils.isEmpty(name)) {
            return AjaxResult.error("规格名不能为空");
        }
        List<MallBrand> mallGoodsBrands = mallBrandService.findByName(name);
        if (mallGoodsBrands.size() > 0) {
            if (StringUtils.isEmpty(id)) {
                return AjaxResult.error("品牌名称已存在");
            }
            boolean flag = false;
            for (MallBrand db : mallGoodsBrands) {
                if (db.getId().equals(id)) {
                    flag = true;
                    break;
                }
            }
            if (flag) {
                return AjaxResult.success();
            } else {
                return AjaxResult.error("品牌名称已存在");
            }
        }
        return AjaxResult.success();
    }

    @ResponseBody
    @RequestMapping("initQrCode")
    public AjaxResult initQrCode() {
        List<MallBrand> brands = mallBrandService.list(new MallBrand());
        for (MallBrand mallBrand : brands) {
            mallBrandBizService.initQrCode(mallBrand.getId());
        }
        return AjaxResult.success();
    }
}
